#ifndef SNAPSHOTLISTFINDER_CPP
#define SNAPSHOTLISTFINDER_CPP

#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>

#include <dirent.h>
#include <cstring>

using namespace std;

class SnapshotListFinder {
		
	public:
		int SnapshotFormat;
		int NumFilesPerSnapshot;
		int FirstSnapshotID;
		int TotalSnapshotNum;
		string SnapshotFileBase;
		string SnapshotsFolder;
		string SnapshotIDFormat;
		
		int getList(string FullFileName){

			// produce filename decomposition!!!
			size_t nP = FullFileName.find_last_of("/");
			size_t nR = FullFileName.length()-1;
			
			SnapshotsFolder = FullFileName.substr(0, nP);
			string FileName = FullFileName.substr(nP+1, nR);
			
			getList(SnapshotsFolder, FileName);
			
		}
		
		int getList(string folder, string SnapshotFileName){
			 
			// filename decomposition 
			size_t nR, nP, nIDL, nIDR;
			nR = SnapshotFileName.length()-1;
			nP = SnapshotFileName.find_first_of(".");
			nIDL = SnapshotFileName.find_first_of("0123456789");
			nP==string::npos ? nIDR = nR : nIDR = nP-1;
				
			// SnapshotIDFormat
			char temp[10];
			sprintf(temp, "%%0%uu", nIDR-nIDL+1);
			SnapshotIDFormat = temp;	
			
			// SnapshotFileBase
			SnapshotFileBase=SnapshotFileName.substr(0, nIDL);
			
			// folder openning
			DIR *dir;
			struct dirent *ent;
			if ((dir=opendir(folder.c_str())) == NULL) {
				perror("opendir");
				return -1;
			}
			
			// files reading
			int snapshotIDMax=0;
			int snapshotIDMin=9999999;
			
			TotalSnapshotNum = 0;
			NumFilesPerSnapshot = 1;
			
			while ((ent=readdir(dir)) != false) {
				
				string filename = ent->d_name;
				if (filename.find(SnapshotFileBase)!=string::npos) {
					
					int snapshotID =			
					
					// get first and last snapshot ID
					if (snapshotID<snapshotIDMin) snapshotIDMin=snapshotID;
					if (snapshotID>snapshotIDMax) snapshotIDMax=snapshotID;
					
					//get number of files per snapshot
					if (nP!=string::npos){
						int SnapshotPartNum = atoi(filename.substr(nP+1, nR).c_str());
						printf("%u\n", SnapshotPartNum);
						if (SnapshotPartNum>NumFilesPerSnapshot) NumFilesPerSnapshot = SnapshotPartNum;
						if (SnapshotPartNum>1) continue;
					}
					
					TotalSnapshotNum++;
				}
			
			}
			
			closedir(dir);
			
			FirstSnapshotID = snapshotIDMin;
			if (snapshotIDMax-snapshotIDMin+1!=TotalSnapshotNum) 	perror("file sequence error");
		}
};

#endif